package com.mytijian.code.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;

import com.alibaba.fastjson.JSON;
import com.mytijian.code.enums.SendCodeStatusEnum;
import com.mytijian.code.exceptions.MashangExceptionEnum;
import com.mytijian.code.model.MerchantOrder;
import com.mytijian.code.param.ModifyMobileParam;
import com.mytijian.code.service.helper.ExecutorServiceHelper;
import com.mytijian.code.service.helper.TransactionHelper;
import com.mytijian.code.service.utils.MerchantOrderUtil;
import com.mytijian.exception.BizSystemException;

/**
 * Created by shjh on 2017/9/27.
 */
@Service
public class OrderUserInfoServiceImpl implements OrderUserInfoService {
	
    private Logger logger = LoggerFactory.getLogger(OrderUserInfoServiceImpl.class);

    @Autowired
    private MerchantOrderService merchantOrderService;
    @Autowired
    private TransactionHelper transactionHelper;
    @Autowired
    private ExecutorServiceHelper executorServiceHelper;
    @Autowired
    private SendCodeService sendCodeService;

    @Override
    public void acceptModifyMobile(ModifyMobileParam param) {
        logger.info("修改手机号开始param: " + JSON.toJSONString(param));

        MerchantOrder order = merchantOrderService.selectByOuterId(param.getOuterId());
        MerchantOrderUtil.validateOrderIsExpired(order, param.getOuterId());

        TransactionStatus status = transactionHelper.beginTransaction();
        try {
            order.setMobile(param.getMobile());

            order.setSendCodeStatus(SendCodeStatusEnum.UN_RESEND.getCode());
            order.setAvailableNum(param.getAvailableNum());
            merchantOrderService.updateTmOrder(order, null);
            transactionHelper.commit(status);
        } catch (Exception ex) {
            transactionHelper.rollback(status);
            throw new BizSystemException(MashangExceptionEnum.SYSTEM_ERROR, ex);
        }
        //执行重新发码线程
		executorServiceHelper.submit(() -> sendCodeService.resendCode(order));

        logger.info("天猫订单{}把手机号修改为{}", param.getOuterId(), param.getMobile());
    }
}
